package net.zhengxinyun.performance.controller.exam;

import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.data.SelectOptionBean;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.AnswerFilter;
import net.zhengxinyun.performance.filter.EvaluateUserFilter;
import net.zhengxinyun.performance.filter.ExamQuestionFilter;
import net.zhengxinyun.performance.service.exam.answer.AnswerService;
import net.zhengxinyun.performance.service.exam.exam.ExamService;
import net.zhengxinyun.performance.service.exam.examClass.ExamIndexService;
import net.zhengxinyun.performance.service.exam.select.SelectionService;
import net.zhengxinyun.performance.service.login.EvaluateUserService;
import net.zhengxinyun.performance.service.login.LoginService;
import net.zhengxinyun.performance.service.login.TokenService;
import org.omg.CORBA.ObjectHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测评作答表
 */
@RestController
@RequestMapping("/answer")
public class AnswerCtrl {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private AnswerService answerService;
    @Autowired
    private ExamService examService;
    @Autowired
    private SelectionService selectionService;

    @Autowired
    private ExamIndexService examIndexService;
    @Autowired
    private EvaluateUserService evaUserService;

    /**
     * 测评问卷 试题
     * @param param
     * @return
     */
    @PostMapping("/queryExam")
    public Result<HashMap<String,Object>> getExam(@RequestBody AnswerParm param)
    {


        //有登陆
        if(tokenService.compareToken(param.tokenEntity.getValue()))
        {
            UserEntity user  = loginService.getUserByToken(param.tokenEntity);
            HashMap<String, Object> map = answerQuestion(param,user.getUserPhone());
            map.put("userType","1");
            return ResultUtils.getResults(Result.Status.SUCCESS, "查询成功", map);
        }else if(param.tokenEntity.getUserType()==0) { //未登录


            HashMap<String, Object> map = answerQuestion(param,param.examfilter.getUserTel());
            map.put("userType","0");
            int code = (int) map.get("code");
            if(code==500)
            {
                return ResultUtils.getResults(Result.Status.ERROR, map.get("msg")+"", map);
            }
            return ResultUtils.getResults(Result.Status.SUCCESS, "查询成功", map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "查询成功", null);
    }

    /**
     * 出题
     * @param param
     * @return
     */
    public HashMap<String,Object> answerQuestion(AnswerParm param,String tel)
    {


        HashMap<String,Object> map = new HashMap<>();

        param.examfilter.setUserId(tel);
        String examer =param.examfilter.getExamer();//测评对象
        //param.examfilter.setExamId(new Long(45));
        List<ExamQuestionFilter> examList = examService.selectExam(param.examfilter);

        //校验是否在答题对象之一
        EvaluateUserFilter evaUser = new EvaluateUserFilter(tel);
        List<EvaluateUserFilter> query = evaUserService.query(evaUser);
        List<String> listExamers = param.examfilter.getListExamers();
        String examerlists = String.join(",",listExamers);//问卷的测评对象
        //先判断该用户是否存在。
        if(ObjectUtils.isNotBlank(query))
        {
            //return ResultUtils.getResults(Result.Status.ERROR, "您不在测评库中",null);
            String type = query.get(0).getUserType();
            if(!"0".equals(examerlists) && !examerlists.contains(type))
            {
                map.put("msg","您不在当前测评范围内，换个测评重新测试吧！^_^ ");
                map.put("code",500);
                return map;
            }

        }else { //为空就新增一个用户

            EvaluateUserEntity newEvauser= new EvaluateUserEntity();
            newEvauser.setPhone(tel);
            newEvauser.setUserType("0");
            newEvauser.setDepartment("暂无");

            newEvauser.setName("YT_"+Util.randomChar(6));

            evaUserService.insert(newEvauser);
            if(!"0".equals(examerlists))   //无限制的条件下，可以直接进入答题
            {
                map.put("msg","您不在当前测评范围内，换个测评重新测试吧！^_^ ");
                map.put("code",500);
                return map;
            }

        }


        //进入答题页
        map.put("code",200);
        AnswerFilter ansfilter  = new AnswerFilter();
        ansfilter.setUserId(tel);
        ansfilter.setExamId(param.examfilter.getExamId());
        Integer count = answerService.queryForCount(ansfilter);
        ExamIndex examIndex = examIndexService.selectByPrimaryKey(param.examfilter.getExamId());



        List<Map<String,Object> >  oplist = new ArrayList<>();

        List<Map<String,Object> >  exlist = new ArrayList<>();
        for (ExamQuestionFilter exam : examList) {
            HashMap<String,Object> mapexam = new HashMap<>();
            mapexam.put("examId",exam.getExamId());
            mapexam.put("questionId",exam.getId());
            mapexam.put("stem",exam.getStem());
            mapexam.put("optionId",exam.getOptionId());
            mapexam.put("selectId",exam.getAnswer());
            mapexam.put("examName",examIndex.getExamName());
            if ("2".equals(examIndex.getExamType())) {
                mapexam.put("departCode",param.examfilter.getDepartCode());
            }else {
                mapexam.put("departCode",exam.getDepartCode());
            }
            mapexam.put("examer",examer);
            List<SelectOptionBean> selectList = Util.setSelectList(exam);
            mapexam.put("selectList",selectList);
            exlist.add(mapexam);

        }

        map.put("list",exlist);

        map.put("answered",count);
        return  map;
    }


    /**
     * 答题暂存  需要登录
     * @param param
     * @return
     */
    @PostMapping("/insert")
    public Result<String> insertExamIndex(@RequestBody AnswerParm param)
    {

        Long examMagId = param.entity.getExamMagId();

       /* if(ObjectUtils.isBlank(examMagId))
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"examMagid 不能为空");
        }*/

        if(tokenService.compareToken(param.tokenEntity.getValue())) {
            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            param.entity.setAnswer(param.entity.getSelectId());
            param.entity.setUserId(userEntity.getUserPhone());
        }else
        {       //设置用户的手机号

          param.entity.setAnswer(param.entity.getSelectId());
          String tel  = param.entity.getUserTel();
          if(StringUtils.isBlank(tel))
          {
              return  ResultUtils.getResults(Result.Status.ERROR,"手机号不能为空");
          }
          param.entity.setUserId(tel);
        }
            param.entity.setExamMagId(examMagId);
            AnswerEntity entity = answerService.selectCahche(param.entity);
            if(ObjectUtils.isNotBlank(entity))
            {
                entity.setAnswer(param.entity.getSelectId());
                int i  =answerService.updateCache(entity);
                if(i ==0){
                    return ResultUtils.getResults(Result.Status.ERROR,"操作失败");
                }
            }else
            {
                int insert = answerService.saveCache(param.entity);
                if(insert ==0){
                    return ResultUtils.getResults(Result.Status.ERROR,"操作失败");
                }
            }



            return ResultUtils.getResults(Result.Status.SUCCESS,"操作成功");




      //  return ResultUtils.getResults(Result.Status.OVERTIME, "登录过期");
    }



    /**
     * 保存答题
     * @param param
     * @return
     */
    @PostMapping("/saveAnswer")
    public Result<String> saveExamIndex(@RequestBody AnswerParm param)
    {
        if(tokenService.compareToken(param.tokenEntity.getValue()))
        {

            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            answerService.save(param.filter.getSelectList(),userEntity);
            return ResultUtils.getResults(Result.Status.SUCCESS,"操作成功");
        }else if("false".equals(param.tokenEntity.getValue())){
            UserEntity user  = new UserEntity();
            if(StringUtils.isBlank(param.filter.getUserTel()))
            {
                return ResultUtils.getResults(Result.Status.ERROR,"手机号不能为空");
            }
            user.setUserPhone(param.filter.getUserTel());
            answerService.save(param.filter.getSelectList(),user);
            return ResultUtils.getResults(Result.Status.SUCCESS,"操作成功");
        }

        return ResultUtils.getResults(Result.Status.OVERTIME, "登录过期");



    }





}
class AnswerParm
{
    public AnswerEntity entity;
    public AnswerFilter filter;
    public ExamQuestionFilter examfilter;
    public TokenEntity tokenEntity;

}